package com.yehui.alibaba.service.at.impl;

import com.yehui.alibaba.service.at.ATService;
import com.yehui.alibaba.service.at.AccountService;
import com.yehui.alibaba.service.at.OrderService;
import com.yehui.alibaba.service.at.ProductService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 业徽
 * @date 2021/8/5
 */
@Service("atService")
public class ATServiceImpl implements ATService {

    private static final Logger logger = LoggerFactory.getLogger(ATServiceImpl.class);

    @Resource
    private ProductService productService;

    @Resource
    private AccountService accountService;

    @Resource
    private OrderService orderService;

    /**
     * 使用 tcc
     *
     * @param userId
     * @param productId
     * @param price
     * @return
     * @throws Exception
     */
    @Override
    @GlobalTransactional
    public Integer createOrder(Long userId, Long productId, Integer price) throws Exception {
        Integer amount = 1; // 购买数量，暂时设置为 1。

        logger.info("[createOrder] 当前 XID: {}", RootContext.getXID());

        // 扣减库存
        productService.reduceStock(productId, amount);

        // 扣减余额
        accountService.reduceBalance(userId, price);

        // 保存订单
        final Integer orderId = orderService.add(null, userId, productId, amount * price);
        logger.info("[createOrder] 保存订单: {}", orderId);

        // 返回订单编号
        return orderId;
    }
}
